
package com.epam.android.training.level1.service;

import com.epam.android.training.level1.activity.IntentActions;
import com.epam.android.training.level1.activity.SettingsActivity;
import com.epam.android.training.level1.db.dao.RssDao;
import com.epam.android.training.level1.db.dao.impl.RssDaoImpl;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.text.format.DateUtils;

import java.util.Timer;
import java.util.TimerTask;

/**
 * @author Anton Novikau
 */
public class RssSyncService extends Service implements IntentActions {
  private RssDao rssDao;

  private Timer syncTimer;

  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    String interval = prefs.getString(SettingsActivity.RSS_REFRESH_INTERVAL_KEY, "0");

    rssDao = new RssDaoImpl(this);
    syncTimer = new Timer("SychFeedsThread");
    syncTimer
        .schedule(new SyncFeedTask(), 0, Long.parseLong(interval) * DateUtils.MINUTE_IN_MILLIS);
  }

  @Override
  public void onDestroy() {
    syncTimer.cancel();
    super.onDestroy();
  };

  private class SyncFeedTask extends TimerTask {

    @Override
    public void run() {
      rssDao.syncFeeds();
      sendBroadcast(new Intent(ACTION_RENEW_WIDGET));
    }
  }
}
